package com.ruoyi.stuclient.api;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.jwt.JWT;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.domain.ThirdSession;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.stuclient.domain.EwcClass;
import com.ruoyi.stuclient.domain.EwcStudent;
import com.ruoyi.stuclient.domain.dto.StudentLoginDto;
import com.ruoyi.stuclient.domain.vo.StudentLoginVo;
import com.ruoyi.stuclient.service.IEwcClassService;
import com.ruoyi.stuclient.service.IEwcStudentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author zsp
 * @date 2025年03月18日 06：34
 */
@Slf4j
@Validated
@RestController
@Tag(name = "用户登录接口", description = "学生登录")
@RequestMapping("/api/studentClient")
public class StudentLoginApi {

    @Autowired
    private IEwcStudentService iEwcStudentService;

    @Autowired
    private IEwcClassService iEwcClassService;


    @Autowired
    private RedisService redisService;
    /**
     * 学生登录
     * @param studentLoginDto
     * @return AjaxResult
     */
    @Operation(summary = "学生登录")
    @PostMapping("/studentLogin")
    public AjaxResult studentLogin(@Valid @RequestBody StudentLoginDto studentLoginDto) {
        //解密密码
        AES aes = new AES("CBC", "PKCS7Padding", Constants.AES_KEY.getBytes(), Constants.AES_IV.getBytes());
        String password=aes.decryptStr(studentLoginDto.getPassword(), CharsetUtil.CHARSET_UTF_8);
        //验证登录信息
        StudentLoginVo studentLoginVo = iEwcStudentService.getLoginInfoByStudentNo(studentLoginDto.getStudentNo());
        if (Objects.isNull(studentLoginVo) || !Objects.equals(studentLoginVo.getPassword(), DigestUtil.md5Hex(password))){
            return AjaxResult.error("账户或密码错误");
        }
        //生成token
        String token = JWT.create()
                .setPayload("timestamp", System.currentTimeMillis())//过期时间
                .setPayload("uid", studentLoginVo.getStudentId())//用户id
                .setKey(Constants.AES_KEY.getBytes())//授权密钥
                .sign();
        ThirdSession thirdSessionStudent = new ThirdSession();
        thirdSessionStudent.setId(studentLoginVo.getStudentId());
        thirdSessionStudent.setStudentNo(studentLoginVo.getStudentNo());
        thirdSessionStudent.setStudentName(studentLoginVo.getStudentName());
        thirdSessionStudent.setGender(studentLoginVo.getGender());
        thirdSessionStudent.setAvatarPath(studentLoginVo.getAvatarPath());
        thirdSessionStudent.setMobile(studentLoginVo.getMobileNo());
        thirdSessionStudent.setSchoolId(studentLoginVo.getSchoolId());
        //查询班级信息
//      EwcClass ewcClass = iEwcClassService.getClassByStudentId(student.getId());
//      if(Objects.nonNull(ewcClass)){
//          thirdSessionStudent.setClassName(ewcClass.getClassName());
//          thirdSessionStudent.setClassGrade(ewcClass.getClassGrade());
//      }
        redisService.setCacheObject(CacheConstants.API_TOKEN_CACHE + token, JSONObject.toJSONString(thirdSessionStudent), 30L, TimeUnit.DAYS);
        log.info("学生登录成功");
        JSONObject resultJson = new JSONObject();
        resultJson.put("token", token);
        resultJson.put("studentInfo", thirdSessionStudent);
        return AjaxResult.success("登录成功", resultJson);
    }

    /**
     * 学生登录退出
     * @return 学生登录退出
     */
    @Operation(summary = "学生登录退出")
    @RequestMapping("/studentLogout")
    public AjaxResult studentLogout(@RequestHeader("third-session") String token){
        redisService.deleteObject(CacheConstants.API_TOKEN_CACHE+token);
        return AjaxResult.success("退出成功");
    }
}
